package com.shlh.saas.service;

import com.shlh.saas.entity.canton.buyer.BaseCantonFairBuyer;
import com.shlh.saas.entity.canton.exhibitor.BaseCantonFairExhibitor;
import com.shlh.saas.entity.company.Company;
import com.shlh.saas.entity.facebook.FacebookUser;
import com.shlh.saas.entity.linkedin.LinkedInUser;
import com.shlh.saas.entity.twitter.TwitterUser;
import com.shlh.saas.mapper.canton.buyer.CantonFairBuyerMapper;
import com.shlh.saas.mapper.canton.exhibitor.CantonFairExhibitorMapper;
import com.shlh.saas.mapper.company.CompanyMapper;
import com.shlh.saas.mapper.facebook.FacebookUserMapper;
import com.shlh.saas.mapper.linkedin.LinkedInUserMapper;
import com.shlh.saas.mapper.twitter.TwitterUserMapper;
import com.shlh.saas.service.company.CompanyService;
import com.shlh.saas.service.facebook.FacebookEsService;
import com.shlh.saas.service.facebook.FacebookUserService;
import com.shlh.saas.service.linkedin.LinkedInUserService;
import com.shlh.saas.service.twitter.TwitterEsService;
import com.shlh.saas.service.twitter.TwitterService;
import com.shlh.saas.util.QueryUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * 智能搜邮服务
 * 通过关键词在多个数据源中搜索邮箱和电话信息
 */
@Slf4j
@Service
public class IntelligentSearchService {

    @Autowired
    private FacebookUserService facebookService;

    @Autowired
    private TwitterService twitterService;

    @Autowired
    private LinkedInUserService linkedInUserService;
    
    @Autowired
    private CompanyService companyService;
    
    @Autowired
    private CantonFairBuyerMapper cantonFairBuyerMapper;
    
    @Autowired
    private CantonFairExhibitorMapper cantonFairExhibitorMapper;

    /**
     * 搜索邮箱或电话数据
     * @param keyword 搜索关键词
     * @param type 搜索类型 (email/phone)
     * @param page 页码
     * @param size 每页记录数
     * @return 搜索结果和统计信息
     */
    public Map<String, Object> searchData(String keyword, String type, int page, int size) {
        // 计算分页参数
        int offset = (page - 1) * size;

        // 统一搜索关键词格式
        String searchKeyword = keyword.trim();

        // 创建异步任务列表，同时查询多个数据源提高效率
        List<CompletableFuture<List<Map<String, Object>>>> dataTasks = new ArrayList<>();
        List<CompletableFuture<Long>> countTasks = new ArrayList<>();

        // 1. 搜索Facebook数据
        CompletableFuture<List<Map<String, Object>>> facebookDataTask = CompletableFuture.supplyAsync(() -> {
            try {
                List<FacebookUser> results;
                long totalCount;
                
                if ("email".equals(type)) {
                    // 使用安全执行查询方法
                    results = QueryUtil.safeExecuteQuery(() ->
                            facebookService.searchFacebookUsersWithEmail(searchKeyword, offset, size));
                    totalCount = QueryUtil.safeExecuteCount(() ->
                            facebookService.countFacebookUsersWithEmail(searchKeyword));
        } else {
                    // 使用安全执行查询方法
                    results = QueryUtil.safeExecuteQuery(() ->
                            facebookService.searchFacebookUsersWithPhone(searchKeyword, offset, size));
                    totalCount = QueryUtil.safeExecuteCount(() ->
                            facebookService.countFacebookUsersWithPhone(searchKeyword));
                }
                
                // 记录总数以便后续统计
                facebookTotalCount = totalCount;
                
                // 转换为通用结果格式
                return results.stream().map(this::convertFacebookUserToMap).collect(Collectors.toList());
            } catch (Exception e) {
                e.printStackTrace();
                return new ArrayList<>();
            }
        });
        
        CompletableFuture<Long> facebookCountTask = CompletableFuture.supplyAsync(() -> facebookTotalCount);
        dataTasks.add(facebookDataTask);
        countTasks.add(facebookCountTask);

        // 2. 搜索Twitter数据
        CompletableFuture<List<Map<String, Object>>> twitterDataTask = CompletableFuture.supplyAsync(() -> {
            try {
                List<TwitterUser> results;
                long totalCount;
                
                if ("email".equals(type)) {
                    // 使用安全执行查询方法
                    results = QueryUtil.safeExecuteQuery(() ->
                            twitterService.searchTwitterUsersWithEmail(searchKeyword, offset, size));
                    totalCount = QueryUtil.safeExecuteCount(() ->
                            twitterService.countTwitterUsersWithEmail(searchKeyword));
        } else {
                    results = new ArrayList<>();
                    totalCount = 0L;
                }
                
                // 记录总数以便后续统计
                twitterTotalCount = totalCount;
                
                // 转换为通用结果格式
                return results.stream().map(this::convertTwitterUserToMap).collect(Collectors.toList());
            } catch (Exception e) {
                e.printStackTrace();
                return new ArrayList<>();
            }
        });
        
        CompletableFuture<Long> twitterCountTask = CompletableFuture.supplyAsync(() -> twitterTotalCount);
        dataTasks.add(twitterDataTask);
        countTasks.add(twitterCountTask);

        // 3. 搜索LinkedIn数据
        CompletableFuture<List<Map<String, Object>>> linkedInDataTask = CompletableFuture.supplyAsync(() -> {
            try {
                List<LinkedInUser> results;
                long totalCount;

                if ("email".equals(type)) {
                    // 使用安全执行查询方法
                    results = QueryUtil.safeExecuteQuery(() -> 
                        linkedInUserService.searchLinkedInUsersWithEmail(searchKeyword, offset, size));
                    totalCount = QueryUtil.safeExecuteCount(() -> 
                        linkedInUserService.countLinkedInUsersWithEmail(searchKeyword));
                } else {
                    // 使用安全执行查询方法
                    results = QueryUtil.safeExecuteQuery(() -> 
                        linkedInUserService.searchLinkedInUsersWithPhone(searchKeyword, offset, size));
                    totalCount = QueryUtil.safeExecuteCount(() -> 
                        linkedInUserService.countLinkedInUsersWithPhone(searchKeyword));
                }
                
                // 记录总数以便后续统计
                linkedInTotalCount = totalCount;
                
                // 转换为通用结果格式
                return results.stream().map(this::convertLinkedInUserToMap).collect(Collectors.toList());
            } catch (Exception e) {
                e.printStackTrace();
                return new ArrayList<>();
            }
        });
        
        CompletableFuture<Long> linkedInCountTask = CompletableFuture.supplyAsync(() -> linkedInTotalCount);
        dataTasks.add(linkedInDataTask);
        countTasks.add(linkedInCountTask);
        
        // 4. 搜索全球企业库数据
        CompletableFuture<List<Map<String, Object>>> companyDataTask = CompletableFuture.supplyAsync(() -> {
            try {
                List<Company> results;
                long totalCount;
                
                if ("email".equals(type)) {
                    // 使用安全执行查询方法
                    results = QueryUtil.safeExecuteQuery(() -> 
                        companyService.searchCompaniesWithEmail(searchKeyword, offset, size));
                    totalCount = QueryUtil.safeExecuteCount(() -> 
                        companyService.countCompaniesWithEmail(searchKeyword));
                } else {
                    // 使用安全执行查询方法
                    results = QueryUtil.safeExecuteQuery(() -> 
                        companyService.searchCompaniesWithPhone(searchKeyword, offset, size));
                    totalCount = QueryUtil.safeExecuteCount(() -> 
                        companyService.countCompaniesWithPhone(searchKeyword));
                }
                
                // 记录总数以便后续统计
                companyTotalCount = totalCount;
                
                // 转换为通用结果格式
                return results.stream().map(this::convertCompanyToMap).collect(Collectors.toList());
                } catch (Exception e) {
                    e.printStackTrace();
                    return new ArrayList<>();
                }
            });
            
        CompletableFuture<Long> companyCountTask = CompletableFuture.supplyAsync(() -> companyTotalCount);
        dataTasks.add(companyDataTask);
        countTasks.add(companyCountTask);

        // 5. 搜索广交会采购商数据
        CompletableFuture<List<Map<String, Object>>> buyerDataTask = CompletableFuture.supplyAsync(() -> {
                try {
                List<BaseCantonFairBuyer> results;
                long totalCount;
                
                if ("email".equals(type)) {
                    // 使用安全执行查询方法
                    results = QueryUtil.safeExecuteQuery(() -> 
                        cantonFairBuyerMapper.searchBuyersWithEmail(searchKeyword, offset, size));
                    totalCount = QueryUtil.safeExecuteCount(() -> 
                        cantonFairBuyerMapper.countBuyersWithEmail(searchKeyword));
                } else {
                    results = QueryUtil.safeExecuteQuery(() ->
                            cantonFairBuyerMapper.searchBuyersWithPhone(searchKeyword, offset, size));
                    totalCount = QueryUtil.safeExecuteCount(() ->
                            cantonFairBuyerMapper.countBuyersWithPhone(searchKeyword));
                    }
                    
                // 记录总数以便后续统计
                buyerTotalCount = totalCount;
                
                // 转换为通用结果格式
                return results.stream().map(this::convertBuyerToMap).collect(Collectors.toList());
                } catch (Exception e) {
                    e.printStackTrace();
                    return new ArrayList<>();
                }
            });
            
        CompletableFuture<Long> buyerCountTask = CompletableFuture.supplyAsync(() -> buyerTotalCount);
        dataTasks.add(buyerDataTask);
        countTasks.add(buyerCountTask);

        // 6. 搜索广交会展商数据
        CompletableFuture<List<Map<String, Object>>> exhibitorDataTask = CompletableFuture.supplyAsync(() -> {
            try {
                List<BaseCantonFairExhibitor> results;
                long totalCount;
                
                if ("email".equals(type)) {
                    // 使用安全执行查询方法
                    results = QueryUtil.safeExecuteQuery(() -> 
                        cantonFairExhibitorMapper.searchExhibitorsWithEmail(searchKeyword, offset, size));
                    totalCount = QueryUtil.safeExecuteCount(() -> 
                        cantonFairExhibitorMapper.countExhibitorsWithEmail(searchKeyword));
        } else {
                    // 对于可能存在问题的查询，直接返回空列表
                    results = Collections.emptyList();
                    totalCount = 0;
                }
                
                // 记录总数以便后续统计
                exhibitorTotalCount = totalCount;

                // 转换为通用结果格式
                return results.stream().map(this::convertExhibitorToMap).collect(Collectors.toList());
            } catch (Exception e) {
                e.printStackTrace();
                return new ArrayList<>();
            }
        });
        
        CompletableFuture<Long> exhibitorCountTask = CompletableFuture.supplyAsync(() -> exhibitorTotalCount);
        dataTasks.add(exhibitorDataTask);
        countTasks.add(exhibitorCountTask);

        // 收集所有数据源的结果
        List<Map<String, Object>> allResults = new ArrayList<>();
        long total = 0;

        try {
            // 合并所有数据结果
            for (CompletableFuture<List<Map<String, Object>>> task : dataTasks) {
                allResults.addAll(task.get());
            }
            log.info("合并所有数据结果完成，allResult={}", allResults);

            // 合并总数
            for (CompletableFuture<Long> task : countTasks) {
                Long count = task.get();
                total += count != null ? count : 0;
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            // 发生异常时返回空结果
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("results", Collections.emptyList());
            errorResponse.put("total", 0);
            errorResponse.put("page", page);
            errorResponse.put("size", size);
            errorResponse.put("error", "搜索过程中发生错误: " + e.getMessage());
            return errorResponse;
        }

        // 排序结果 - 主要按照相关度排序，其次按来源排序
        allResults.sort((a, b) -> {
            // 计算相关度得分（得分越高，排名越靠前）
            int relevanceScoreA = calculateRelevanceScore(a, searchKeyword);
            int relevanceScoreB = calculateRelevanceScore(b, searchKeyword);
            
            // 按相关度得分排序（降序）
            if (relevanceScoreA != relevanceScoreB) {
                return Integer.compare(relevanceScoreB, relevanceScoreA);
            }
            
            // 如果相关度得分相同，按来源排序
            String sourceA = (String) a.get("source");
            String sourceB = (String) b.get("source");
            
            // 首先按来源排序
            int sourceCompare = sourceA.compareTo(sourceB);
            if (sourceCompare != 0) {
                return sourceCompare;
            }
            
            // 最后按名称字母顺序排序
            String nameA = getNameFromResult(a);
            String nameB = getNameFromResult(b);
            return nameA.compareTo(nameB);
        });

        log.info("排序结果完成，allResult={}", allResults);
        
        // 分页处理结果
//        int fromIndex = Math.min(allResults.size(), offset);
//        int toIndex = Math.min(allResults.size(), offset + size);
        List<Map<String, Object>> pagedResults = new ArrayList<>();
        if (allResults.isEmpty()) {
            log.info("无数据");
        } else {
            int endIndex = Math.min(10, allResults.size());
            pagedResults = allResults.subList(0, endIndex);
            log.info("分页处理结果完成，pagedResult={}", pagedResults);
        }

        // 返回结果
        Map<String, Object> response = new HashMap<>();
        response.put("results", pagedResults);
        response.put("total", total);
        response.put("page", page);
        response.put("size", size);
        
        return response;
    }
    
    // 用于存储各数据源的总记录数
    private long facebookTotalCount = 0;
    private long twitterTotalCount = 0;
    private long linkedInTotalCount = 0;
    private long companyTotalCount = 0;
    private long buyerTotalCount = 0;
    private long exhibitorTotalCount = 0;
    
    /**
     * 从结果中获取名称字段
     */
    private String getNameFromResult(Map<String, Object> result) {
        // 按优先级获取名称字段
        if (result.containsKey("name") && result.get("name") != null) {
            return (String) result.get("name");
        } else if (result.containsKey("full_name") && result.get("full_name") != null) {
            return (String) result.get("full_name");
        } else if (result.containsKey("company_name") && result.get("company_name") != null) {
            return (String) result.get("company_name");
        } else {
            return "";
        }
    }
    
    /**
     * 检查关键词是否出现在联系信息（邮箱或电话）中
     */
    private boolean isKeywordInContactInfo(Map<String, Object> result, String keyword) {
        String lowerKeyword = keyword.toLowerCase();
        
        // 检查邮箱
        if (result.containsKey("email") && result.get("email") != null) {
            String email = ((String) result.get("email")).toLowerCase();
            if (email.contains(lowerKeyword)) {
                return true;
            }
        }
        if (result.containsKey("emails") && result.get("emails") != null) {
            String emails = ((String) result.get("emails")).toLowerCase();
            if (emails.contains(lowerKeyword)) {
                return true;
            }
        }
        
        // 检查电话
        if (result.containsKey("phone") && result.get("phone") != null) {
            String phone = ((String) result.get("phone")).toLowerCase();
            if (phone.contains(lowerKeyword)) {
                return true;
            }
        }
        if (result.containsKey("phone_numbers") && result.get("phone_numbers") != null) {
            String phoneNumbers = ((String) result.get("phone_numbers")).toLowerCase();
            if (phoneNumbers.contains(lowerKeyword)) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * 计算结果的相关度得分
     * 得分规则：
     * - 关键词在姓名/全名中：+10分
     * - 关键词在公司名称中：+8分
     * - 关键词在邮箱中：+6分
     * - 关键词在电话中：+6分
     * - 关键词在网址中：+4分
     * - 关键词在其他字段中：+2分
     */
    private int calculateRelevanceScore(Map<String, Object> result, String keyword) {
        int score = 0;
        String lowerKeyword = keyword.toLowerCase();
        
        // 检查姓名/全名
        String name = getNameFromResult(result);
        if (name.toLowerCase().contains(lowerKeyword)) {
            score += 10;
        }
        
        // 检查公司名称
        if (result.containsKey("company_name") && result.get("company_name") != null) {
            String companyName = ((String) result.get("company_name")).toLowerCase();
            if (companyName.contains(lowerKeyword)) {
                score += 8;
            }
        }
        
        // 检查邮箱
        if (result.containsKey("email") && result.get("email") != null) {
            String email = ((String) result.get("email")).toLowerCase();
            if (email.contains(lowerKeyword)) {
                score += 6;
            }
        }
        if (result.containsKey("emails") && result.get("emails") != null) {
            String emails = ((String) result.get("emails")).toLowerCase();
            if (emails.contains(lowerKeyword)) {
                score += 6;
            }
        }
        
        // 检查电话
        if (result.containsKey("phone") && result.get("phone") != null) {
            String phone = ((String) result.get("phone")).toLowerCase();
            if (phone.contains(lowerKeyword)) {
                score += 6;
            }
        }
        if (result.containsKey("phone_numbers") && result.get("phone_numbers") != null) {
            String phoneNumbers = ((String) result.get("phone_numbers")).toLowerCase();
            if (phoneNumbers.contains(lowerKeyword)) {
                score += 6;
            }
        }
        
        // 检查网址
        if (result.containsKey("company_website") && result.get("company_website") != null) {
            String companyWebsite = ((String) result.get("company_website")).toLowerCase();
            if (companyWebsite.contains(lowerKeyword)) {
                score += 4;
            }
        }
        if (result.containsKey("website") && result.get("website") != null) {
            String website = ((String) result.get("website")).toLowerCase();
            if (website.contains(lowerKeyword)) {
                score += 4;
            }
        }
        if (result.containsKey("web_address") && result.get("web_address") != null) {
            String webAddress = ((String) result.get("web_address")).toLowerCase();
            if (webAddress.contains(lowerKeyword)) {
                score += 4;
            }
        }
        
        // 检查其他可能的字段
        for (Map.Entry<String, Object> entry : result.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            
            // 跳过已经检查过的字段和非字符串字段
            if (key.equals("name") || key.equals("full_name") || key.equals("company_name") ||
                key.equals("email") || key.equals("emails") || key.equals("phone") || 
                key.equals("phone_numbers") || key.equals("company_website") || 
                key.equals("website") || key.equals("web_address") || key.equals("source") ||
                !(value instanceof String)) {
                continue;
            }
            
            // 检查其他字段中是否包含关键词
            String fieldValue = ((String) value).toLowerCase();
            if (fieldValue.contains(lowerKeyword)) {
                score += 2;
            }
        }
        
        return score;
    }
    
    /**
     * 将Facebook用户转换为通用Map格式
     */
    private Map<String, Object> convertFacebookUserToMap(FacebookUser user) {
        Map<String, Object> result = new HashMap<>();
        result.put("id", user.getPhoneNumber());
        
        // 组合firstName和lastName作为完整姓名
        String fullName = "";
        if (user.getFirstName() != null && !user.getFirstName().isEmpty()) {
            fullName += user.getFirstName();
        }
        if (user.getLastName() != null && !user.getLastName().isEmpty()) {
            if (!fullName.isEmpty()) {
                fullName += " ";
            }
            fullName += user.getLastName();
        }
        result.put("name", fullName);
        
        result.put("email", user.getEmail());
        result.put("phone", user.getPhoneNumber());
        
        // 组合currentLocation和hometown作为位置信息
        String location = "";
        if (user.getCurrentLocation() != null && !user.getCurrentLocation().isEmpty()) {
            location = user.getCurrentLocation();
        } else if (user.getHometown() != null && !user.getHometown().isEmpty()) {
            location = user.getHometown();
        }
        result.put("location", location);
        result.put("current_location", user.getCurrentLocation());
        result.put("hometown", user.getHometown());
        
        result.put("gender", user.getGender());
        result.put("facebook_id", user.getFacebookId());
        result.put("workplace", user.getWorkplace());
        result.put("relationship_status", user.getRelationshipStatus());
        result.put("date", user.getDate());
        result.put("join_date", user.getJoinDate());
        result.put("source", "facebook_data");
        return result;
    }
    
    /**
     * 将Twitter用户转换为通用Map格式
     */
    private Map<String, Object> convertTwitterUserToMap(TwitterUser user) {
        Map<String, Object> result = new HashMap<>();
        result.put("id", user.getId());
        result.put("name", user.getName());
        result.put("email", user.getEmail());
        result.put("screen_name", user.getScreenName());
        result.put("followers", user.getFollowers());
        result.put("created_at", user.getCreatedAt());
        result.put("source", "twitter_data");
        return result;
    }
    
    /**
     * 将LinkedIn用户转换为通用Map格式
     */
    private Map<String, Object> convertLinkedInUserToMap(LinkedInUser user) {
        Map<String, Object> result = new HashMap<>();
        result.put("id", user.getId());
        result.put("full_name", user.getFullName());
        result.put("company_name", user.getCompanyName());
        result.put("job_title", user.getJobTitle());
        result.put("industry", user.getIndustry());
        result.put("emails", user.getEmails());
        result.put("phone_numbers", user.getPhoneNumbers());
        result.put("mobile", user.getMobile());
        result.put("location", user.getLocation());
        result.put("company_website", user.getCompanyWebsite());
        result.put("company_size", user.getCompanySize());
        result.put("country", user.getLocationCountry());
        result.put("twitter_username", user.getTwitterUserName());
        result.put("twitter_url", user.getTwitterUrl());
        result.put("linkedin_url", user.getLinkedinUrl());
        result.put("github_url", user.getGithubUrl());
        result.put("facebook_url", user.getFacebookUrl());
        result.put("source", "linkedin_data");
        return result;
    }
    
    /**
     * 将企业信息转换为通用Map格式
     */
    private Map<String, Object> convertCompanyToMap(Company company) {
        Map<String, Object> result = new HashMap<>();
        result.put("id", company.getId());
        result.put("company_name", company.getCompanyName());
        result.put("first_name", company.getFirstName());
        result.put("middle_name", company.getMiddleName());
        result.put("last_name", company.getLastName());
        result.put("title", company.getTitle());
        result.put("web_address", company.getWebAddress());
        result.put("email", company.getEmail());
        if (company.getPhone() != null && !company.getPhone().isEmpty()) {
            result.put("phone", company.getPhone());
        } else {
            result.put("phone", company.getMobile());
        }
        result.put("mobile", company.getMobile());
        result.put("country", company.getCountry());
        result.put("state", company.getPrimaryState());
        result.put("city", company.getPrimaryCity());
        result.put("industry", company.getIndustry());
        result.put("sub_industry", company.getSubIndustry());
        result.put("employee_size", company.getEmployee());
        result.put("revenue_size", company.getReveneu());
        result.put("address", company.getMailingAddress());
        result.put("zip_code", company.getZipCode());
        result.put("source", "global_enterprise_library");
        return result;
    }
    
    /**
     * 将广交会采购商转换为通用Map格式
     */
    private Map<String, Object> convertBuyerToMap(BaseCantonFairBuyer buyer) {
        log.info("buyer={}", buyer.toString());
        Map<String, Object> result = new HashMap<>();
        result.put("id", buyer.getId());
        result.put("company_name", buyer.getCompanyName());
        result.put("contact_person", buyer.getContactPerson());
        result.put("email", buyer.getEmail());
        if (buyer.getTelephone() != null && !buyer.getTelephone().isEmpty()){
            result.put("phone", buyer.getTelephone());
        }else {
            result.put("phone", buyer.getPhone());
        }
        result.put("fax", buyer.getFax());
        result.put("country", buyer.getCountry());
        result.put("address", buyer.getAddress());
        result.put("website", buyer.getWebsite());
        if (buyer.getDemandGoods() != null && !buyer.getDemandGoods().isEmpty()){
            result.put("purchase_type", buyer.getDemandGoods());
        }else {
            result.put("purchase_type", buyer.getProductCategory());
        }
        if (buyer.getZipCode() != null && !buyer.getZipCode().isEmpty()){
            result.put("zip_code", buyer.getZipCode());
        }
        
        // 广交会届数：优先使用sessionsNum字段（数据库的session字段）
        String sessionInfo = buyer.getSessionsNum();
        if (sessionInfo == null || sessionInfo.isEmpty()) {
            // 如果sessionsNum为空，尝试从扩展字段获取
            if (buyer.getExtendedFields() != null && buyer.getExtendedFields().containsKey("sessionInfo")) {
                sessionInfo = buyer.getExtendedFields().get("sessionInfo");
            }
        }
        result.put("session_info", sessionInfo);
        
        // 处理其他扩展字段
        if (buyer.getExtendedFields() != null) {
            if (buyer.getExtendedFields().containsKey("zipCode")) {
                result.put("zip_code", buyer.getExtendedFields().get("zipCode"));
            }
            if (buyer.getExtendedFields().containsKey("product_category")) {
                result.put("purchase_type", buyer.getExtendedFields().get("product_category"));
            }
        }
        
        result.put("source", "canton_fair_purchasers");

        log.info("convertBuyerToMap result={}", result.toString());
        return result;
    }
    
    /**
     * 将广交会展商转换为通用Map格式
     */
    private Map<String, Object> convertExhibitorToMap(BaseCantonFairExhibitor exhibitor) {
        Map<String, Object> result = new HashMap<>();
        result.put("id", exhibitor.getId());
        result.put("company_name", exhibitor.getCompanyName());
        if (exhibitor.getCompanyType() != null && !exhibitor.getCompanyType().isEmpty()) {
            result.put("company_type", exhibitor.getCompanyType());
        }
        if (exhibitor.getCompanyProfile() != null && !exhibitor.getCompanyProfile().isEmpty()) {
            result.put("company_description", exhibitor.getCompanyProfile());
        }
        if (exhibitor.getMainProducts() != null && !exhibitor.getMainProducts().isEmpty()) {
            result.put("main_products", exhibitor.getMainProducts());
        }
        if (exhibitor.getCompanyScale() != null && !exhibitor.getCompanyScale().isEmpty()) {
            result.put("company_size", exhibitor.getCompanyScale());
        }
        if (exhibitor.getRegisteredCapital() != null && !exhibitor.getRegisteredCapital().isEmpty()) {
            result.put("registered_capital", exhibitor.getRegisteredCapital());
        }
        if (exhibitor.getRecentExhibitionHistory() != null && !exhibitor.getRecentExhibitionHistory().isEmpty()) {
            result.put("exhibition_history", exhibitor.getRecentExhibitionHistory());
        }
        result.put("booth_number", exhibitor.getBoothNumber());
        result.put("category", exhibitor.getCategory());
        result.put("email", exhibitor.getEmail());
        result.put("phone", exhibitor.getPhone());
        result.put("mobile", exhibitor.getMobile());
        result.put("website", exhibitor.getWebsite());
        result.put("contact_person", exhibitor.getContactPerson());
        result.put("address", exhibitor.getAddress());
        result.put("zip_code", exhibitor.getPostalCode());
        result.put("province", exhibitor.getProvince());
        result.put("city", exhibitor.getCity());
        result.put("established_year", exhibitor.getEstablishmentYear());
        if (exhibitor.getFax() != null && !exhibitor.getFax().isEmpty()){
            result.put("fax", exhibitor.getFax());
        }
        
        // 广交会届数：优先使用session字段（数据库的session字段）
        String sessionInfo = exhibitor.getSession();
        if (sessionInfo == null || sessionInfo.isEmpty()) {
            // 如果session为空，尝试从扩展字段获取
            if (exhibitor.getExtendedFields() != null && exhibitor.getExtendedFields().containsKey("sessionInfo")) {
                sessionInfo = (String) exhibitor.getExtendedFields().get("sessionInfo");
            }
        }
        result.put("session_info", sessionInfo);
        
        // 处理其他扩展字段
        if (exhibitor.getExtendedFields() != null) {
            if (exhibitor.getExtendedFields().containsKey("country")) {
                result.put("country", exhibitor.getExtendedFields().get("country"));
            }
            if (exhibitor.getExtendedFields().containsKey("companyType")) {
                result.put("company_type", exhibitor.getExtendedFields().get("companyType"));
            }
            if (exhibitor.getExtendedFields().containsKey("companyDescription")) {
                result.put("company_description", exhibitor.getExtendedFields().get("companyDescription"));
            }
            if (exhibitor.getExtendedFields().containsKey("mainProducts")) {
                result.put("main_products", exhibitor.getExtendedFields().get("mainProducts"));
            }
            if (exhibitor.getExtendedFields().containsKey("companyScale")) {
                result.put("company_size", exhibitor.getExtendedFields().get("companyScale"));
            }
            if (exhibitor.getExtendedFields().containsKey("registeredCapital")) {
                result.put("registered_capital", exhibitor.getExtendedFields().get("registeredCapital"));
            }
            if (exhibitor.getExtendedFields().containsKey("exhibitionHistory")) {
                result.put("exhibition_history", exhibitor.getExtendedFields().get("exhibitionHistory"));
            }
            if (exhibitor.getExtendedFields().containsKey("fax")) {
                result.put("fax", exhibitor.getExtendedFields().get("fax"));
            }
        }
        
        result.put("source", "canton_fair_exhibitors");
        return result;
    }

    public List<Map<String, Object>> searchFacebookData(String companyName, String fullName, Integer matchType) {
        List<FacebookUser> results = facebookService.searchFacebookData(companyName, fullName, matchType);

        // 转换为通用结果格式
        return results.stream()
                .map(this::convertFacebookUserToMap)
                .collect(Collectors.toList());
    }

    public List<Map<String, Object>> searchTwitterData(String companyName, String fullName, Integer matchType) {
        // twitter没有phone字段，直接返回空
        if (matchType == 1 || companyName != null){
            return new ArrayList<>();
        }

        List<TwitterUser> results = twitterService.searchTwitterData(companyName, fullName, matchType);

        return results.stream()
               .map(this::convertTwitterUserToMap)
               .collect(Collectors.toList());
    }

    public List<Map<String, Object>> searchLinkedInData(String companyName, String fullName, String website, Integer matchType) {
        List<LinkedInUser> results = linkedInUserService.searchLinkedInData(companyName, fullName, website, matchType);

        return results.stream()
                .map(this::convertLinkedInUserToMap)
                .collect(Collectors.toList());

    }


    public List<Map<String, Object>> searchCompanyData(String companyName, String fullName, String website, Integer matchType) {

        List<Company> results = companyService.searchCompanyData(companyName, fullName, website, matchType);

        return results.stream()
                .map(this::convertCompanyToMap)
                .collect(Collectors.toList());

    }

    public List<Map<String, Object>> searchBuyerData(String companyName, String fullName, String website, Integer matchType) {
        try {
            List<BaseCantonFairBuyer> results;
            if (matchType == 1) {
                results = cantonFairBuyerMapper.searchBuyerDataWithPhone(companyName, fullName, website);
            } else {
                results = cantonFairBuyerMapper.searchBuyerDataWithEmail(companyName, fullName, website);
            }

            if (results == null) {
                log.warn("searchBuyerData返回null，companyName={}, fullName={}, website={}", companyName, fullName, website);
                return new ArrayList<>();
            }

            log.info("searchBuyerData results：{}", results.size());

            return results.stream()
                    .map(this::convertBuyerToMap)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("搜索广交会采购商数据异常: companyName={}, fullName={}, website={}, matchType={}", 
                     companyName, fullName, website, matchType, e);
            return new ArrayList<>();
        }
    }


    public List<Map<String, Object>> searchExhibitorData(String companyName, String fullName, String website, Integer matchType) {
        try {
            List<BaseCantonFairExhibitor> results;
            if (matchType == 1) {
                results = cantonFairExhibitorMapper.searchExhibitorDataWithPhone(companyName, fullName, website);
            } else {
                results = cantonFairExhibitorMapper.searchExhibitorDataWithEmail(companyName, fullName, website);
            }
            
            if (results == null) {
                log.warn("searchExhibitorData返回null，companyName={}, fullName={}, website={}", companyName, fullName, website);
                return new ArrayList<>();
            }
            
            log.info("searchExhibitorData results：{}", results.size());
            
            return results.stream()
                    .map(this::convertExhibitorToMap)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("搜索广交会展商数据异常: companyName={}, fullName={}, website={}, matchType={}", 
                     companyName, fullName, website, matchType, e);
            return new ArrayList<>();
        }
    }
}